<?php

namespace Modules\Admin\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Traits\HasRoles;

class Manage extends Model
{
    protected $table = "admins";
    protected $fillable = ['name','nickname','password','gid','remember_token'];

    /**
     * 角色的中间表关联
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function role()
    {
        return $this->belongsToMany('Modules\Admin\Entities\Role', 'model_has_roles', 'model_id', 'role_id');
    }

    public function group()
    {
        return $this->belongsTo('Modules\Admin\Entities\ChatGroup','gid');
    }


    /**
     * 插入管理员信息
     * @param $userInfo
     */
    public function insertUser($userInfo)
    {
        $user = new \App\Admin();
        $user->fill([
            'name'=>$userInfo['name'],
            'nickname'=>$userInfo['nickname'],
            'gid'=>$userInfo['gid'],
            'password'=> bcrypt(isset($userInfo['password']) ? $userInfo['password'] : 'mmkk891011' ),
            'remember_token' => str_random(10),
        ]);

        $user->save();
        //然后第二步是分配角色
        $user->assignRole($userInfo['rolename']);
    }


    public function updateUser($userInfo)
    {
        $user = \App\Admin::find($userInfo['id']);
        $user->fill([
            'name'=>$userInfo['name'],
            'nickname'=>$userInfo['nickname'],
            'gid'=>$userInfo['gid'],
            'remember_token' => str_random(10),
        ]);
//        密码单独拿出来放置
        if(isset($userInfo['password']) || $userInfo['password'] != null)
        {
            $user->password = bcrypt($userInfo['password']);
        }
        $user->save();

        $user->syncRoles($userInfo['rolename']);
    }


}
